<template>
  <div class="student-manage">
    <div class="page-header">
      <h2>学生管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>
          添加学生
        </el-button>
        <el-button type="danger" :disabled="!selectedStudents.length" @click="handleBatchDelete">
          <el-icon>
            <Delete />
          </el-icon>
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="searchForm.studentId" placeholder="请输入学号" clearable />
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="searchForm.classId" placeholder="请选择班级" clearable>
            <el-option v-for="item in classOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table :data="tableData" border stripe style="width: 100%" @selection-change="handleSelectionChange"
        v-loading="loading">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="studentNo" label="学号" width="120" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="sex" label="性别" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.sex === 1 ? 'primary' : 'success'">
              {{ scope.row.sex === 1 ? '男' : '女' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="class" label="班级" width="120" />
        <el-table-column prop="mobile" label="电话" width="140" />
        <el-table-column prop="address" label="地址" min-width="150" />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">
              <el-icon>
                <Edit />
              </el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              <el-icon>
                <Delete />
              </el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加学生' : '编辑学生'" width="600px"
      @close="handleDialogClose">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" style="padding-right: 20px">
        <el-form-item label="学号" prop="id">
          <el-input v-model="form.id" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" :min="16" :max="30" />
        </el-form-item>
        <el-form-item label="班级" prop="class">
          <el-select v-model="form.class" placeholder="请选择班级">
            <el-option v-for="item in classOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Plus,
  Delete,
  Edit,
  Search,
  Refresh
} from '@element-plus/icons-vue';
import {
  getStudentListAPI
} from '@/api/student';

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const selectedStudents = ref([]);

// 搜索表单
const searchForm = reactive({
  name: '',
  studentId: '',
  classId: ''
});

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 班级选项
const classOptions = ref([
  { label: '计算机1班', value: '计算机1班' },
  { label: '计算机2班', value: '计算机2班' },
  { label: '软件工程1班', value: '软件工程1班' },
  { label: '软件工程2班', value: '软件工程2班' }
]);

// 对话框
const dialogVisible = ref(false);
const dialogType = ref('add'); // 'add' 或 'edit'
const formRef = ref(null);

// 表单数据
const form = reactive({
  id: '',
  name: '',
  gender: '男',
  age: 18,
  class: '',
  phone: '',
  email: '',
  address: ''
});

// 表单验证规则
const rules = {
  id: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { pattern: /^\d{8}$/, message: '学号必须是8位数字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', message: '年龄必须为数字', trigger: 'blur' }
  ],
  class: [
    { required: true, message: '请选择班级', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ]
};

// 获取学生列表
const getStudentList = async () => {
  loading.value = true;
  try {
    const res = await getStudentListAPI({
      page: pagination.currentPage,
      size: pagination.pageSize,
      name: searchForm.name,
      studentId: searchForm.studentId,
      classId: searchForm.classId
    });

    if (res.code === 200) {
      tableData.value = res.data.records || [];
      pagination.total = res.data.total || 0;
    } else {
      ElMessage.error('获取学生列表失败: ' + res.message);
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('获取学生列表失败:', error);
    ElMessage.error('获取学生列表失败');
    tableData.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  getStudentList();
};

// 重置
const handleReset = () => {
  searchForm.name = '';
  searchForm.studentId = '';
  searchForm.classId = '';
  handleSearch();
};

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  getStudentList();
};

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  getStudentList();
};

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedStudents.value = selection;
};

// 添加学生
const handleAdd = () => {
  dialogType.value = 'add';
  dialogVisible.value = true;
  // 重置表单
  form.id = '';
  form.name = '';
  form.gender = '男';
  form.age = 18;
  form.class = '';
  form.phone = '';
  form.email = '';
  form.address = '';
};

// 编辑学生
const handleEdit = (row) => {
  dialogType.value = 'edit';
  dialogVisible.value = true;
  // 填充表单
  form.id = row.id;
  form.name = row.name;
  form.gender = row.gender;
  form.age = row.age;
  form.class = row.class;
  form.phone = row.phone;
  form.email = row.email;
  form.address = row.address;
};

// 删除学生
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除学生 ${row.name} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 这里应该是实际的API调用
      ElMessage.success('删除成功');
      getStudentList();
    })
    .catch(() => {
      // 取消删除
    });
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedStudents.value.length === 0) {
    ElMessage.warning('请选择要删除的学生');
    return;
  }

  ElMessageBox.confirm(`确定要删除选中的 ${selectedStudents.value.length} 名学生吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 这里应该是实际的API调用
      ElMessage.success('批量删除成功');
      getStudentList();
    })
    .catch(() => {
      // 取消删除
    });
};

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 这里应该是实际的API调用
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功');
      dialogVisible.value = false;
      getStudentList();
    }
  });
};

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields();
};

// 初始化
onMounted(() => {
  getStudentList();
});
</script>

<style scoped>
.student-manage {
  padding: 15px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 0 5px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-container {
  background-color: #fff;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.table-container {
  background-color: #fff;
  padding: 12px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .student-manage {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }

  .search-form {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }
}
</style>